package reader;

import model.tsp.Problem;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TspReader {

    public Problem read(String filename) {
        String path = ClassLoader.getSystemResource(filename).getPath();
        //this.getClass().getClassLoader().getResource(filename).getPath();
        BufferedReader data = reader(path);

        List<Integer> xs = new ArrayList<>();
        List<Integer> ys = new ArrayList<>();
        String edgeWeightType = null;
        int row = 1;
        String line;
        while ((line = readLine(data)) != null) {
            if (row == 5) {
                String[] tokens = line.split(":");
                String key = tokens[0].trim();
                String value = tokens[1].trim();
                if (key.equals("EDGE_WEIGHT_TYPE")) {
                    edgeWeightType = value;
                }
            }

            if (row > 6 && !line.equals("EOF")) {
                String[] cols = line.split(" ");
                int x = Integer.parseInt(cols[1].trim());
                int y = Integer.parseInt(cols[2].trim());
                xs.add(x);
                ys.add(y);
            }
            row++;
        }

        close(data);

        return new Problem(xs, ys, edgeWeightType);
    }

    private BufferedReader reader(String file) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return reader;
    }

    private String readLine(BufferedReader reader) {
        try {
            return reader.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void close(BufferedReader reader) {
        try {
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
